using System.Web.Mvc;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public class DisplayText<TModel> : DisplayTextBase<DisplayText<TModel>, TModel> where TModel : class {
		public DisplayText(IModelViewHelper<TModel> helper, string memberName, object value, string id = null) : base(helper, memberName, value, id) { }
	}

	public abstract class DisplayTextBase<T, TModel> : FormElement<T, TModel>
		where T : DisplayTextBase<T, TModel>
		where TModel : class {
		private const string textSuffix = "_Text";

		protected object value { get; private set; }
		private object _nullDisplayValue;

		protected DisplayTextBase(IModelViewHelper<TModel> helper, string memberName, object value, string id = null)
			: base(helper, HtmlTag.Span, memberName, (id ?? memberName + textSuffix)) {
			SetAttribute(HtmlAttribute.Type, "displayText");
			this.value = value;
		}

		public virtual T NullDisplayValue(object value) {
			_nullDisplayValue = value;
			return (T)this;
		}

		protected override TagRenderMode TagRenderMode { get { return TagRenderMode.Normal; } }

		protected override bool UseNameAttribute { get { return false; } }

		protected override void Prepare() {
			var hiddenControl = new Hidden(memberName, value);
			AddAfter(hiddenControl.ToString());
			base.Prepare();
		}

		protected override void SetContent() {
			var finalValue = (value ?? _nullDisplayValue);
			if (finalValue == null) return;
			Builder.InnerHtml = finalValue.ToString();
		}
	}
}
